<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import UserSelectInputDialog from './user-select-input-dialog.vue';

const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void;
  (e: 'update:userId', val: string | undefined): void;
  (e: 'update:userName', val: string | undefined): void;
  (e: 'change', val: any | undefined): void;
}>();

const props = defineProps({
  /**是否显示 */
  visible: {
    type: Boolean,
    default: false,
  },
  userId: {
    type: String,
  },
  userName: {
    type: String,
  },
  multiple: {
    type: Boolean,
    default: false,
  },
});

const UserListSelectDialogRef = ref();

//设置是否显示双向绑定
const visibleModelValue = ref(props.visible);
watch(
  () => props.visible,
  (val) => {
    visibleModelValue.value = val;
  }
);
watch(visibleModelValue, (val) => {
  emit('update:visible', val);
});

//设置用户id双向绑定
const userIdModelValue = ref(props.userId);
watch(
  () => props.userId,
  (val) => {
    userIdModelValue.value = val;
  }
);
watch(userIdModelValue, (val) => {
  emit('update:userId', val);
});

//设置部门名称双向绑定
const userNameModelValue = ref(props.userName);
watch(
  () => props.userName,
  (val) => {
    userNameModelValue.value = val;
  }
);
watch(userNameModelValue, (val) => {
  emit('update:userName', val);
});

const UserListSelectDialogInputState = reactive({
  onSelectClick: () => {
    visibleModelValue.value = true;
  },
  onClearClick: () => {
    userIdModelValue.value = undefined;
    userNameModelValue.value = undefined;
  },
  onChangeUser: (data: any) => {
    if (props.multiple) {
      // 可多个选择
      let userName = '';
      data.forEach((element: any) => {
        userName += ',' + element.userFullname;
      });
      userNameModelValue.value = userName.substring(1);
      emit('change', data);
    } else {
      userIdModelValue.value = data[0].userId;
      userNameModelValue.value = data[0].userFullname;
      emit('change', data[0]);
    }
  },
});
</script>
<template>
  <user-select-input-dialog
    ref="UserListSelectDialogRef"
    v-model:visible="visibleModelValue"
    @ok="UserListSelectDialogInputState.onChangeUser"
  >
    <jxtech-select-input
      v-model:inputValue="userNameModelValue"
      @select-click="UserListSelectDialogInputState.onSelectClick"
      @clear-click="UserListSelectDialogInputState.onClearClick"
    ></jxtech-select-input>
  </user-select-input-dialog>
</template>
